package com.scpii.universal.monitor;

import java.util.Timer;
import java.util.TimerTask;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.scpii.universal.Const;
import com.scpii.universal.Const.CompileConfig;
import com.scpii.universal.concurrent.executor.HttpClientExecutor;
import com.scpii.universal.pb.UniversalProtocol.Cmd;
import com.scpii.universal.pb.UniversalProtocol.GetTaskCS;
import com.scpii.universal.pb.UniversalProtocol.GetTaskSC;
import com.scpii.universal.pb.UniversalProtocol.TaskSC;
import com.scpii.universal.util.Conversion;
import com.scpii.universal.util.ExceptionUtil;
import com.scpii.universal.util.TaskUtil;
import com.scpii.universal.util.TaskUtil.TaskMehod;

/*
 * 从中间层取得编译任务
 */
public class MonitorServer {

	private static final Logger logger = LoggerFactory.getLogger(MonitorServer.class);
	private String url = null;
	
    public void monitor() {
    	//请求数据
    	GetTaskCS.Builder builder = GetTaskCS.newBuilder();
		builder.setOSType(0);
		GetTaskCS cs = builder.build();
		byte[] buffer = cs.toByteArray();
		//生成请求的URL
    	StringBuffer sb = new StringBuffer();
		sb.append(CompileConfig.SERVER_URL).append("?cmd=").append(Cmd.GetTask.getNumber()).append("&data=").append(Conversion.bytesToHexString(buffer));
		url = sb.toString();		
    	Timer timer = new Timer();    	
    	timer.schedule(new LoopTimerTask(), 0, Const.LOOP_GAP);
    }
    
    private class LoopTimerTask extends TimerTask {
		@Override
		public void run() {
		try {		
			
			byte[] byteArrayResponse = HttpClientExecutor.getInstance().executeGet(url);
			if(byteArrayResponse != null) {
				 GetTaskSC sc = GetTaskSC.parseFrom(byteArrayResponse);	
				 //只打印线程池中有数据的情况
				 	//logger.info("请求到" +  sc.getItemList().size() + "任务");
				 for(TaskSC taskSC : sc.getItemList()) {
					 logger.info("请求到任务:" + taskSC);
					 TaskUtil.getInstance().sendTask(TaskMehod.NATIVE, Cmd.GetTask.getNumber(), taskSC.toByteArray());
				 }
			
			int totalTime = 0;
			while(true) {
				Thread.sleep(Const.LOOP_GAP);
				totalTime += Const.LOOP_GAP;
				if(TaskUtil.getInstance().getNativeTaskPool().isCompleted() && TaskUtil.getInstance().getFinishTaskPool().isCompleted()) {
					//logger.info("线程池执行完成");
					Thread.sleep(1000 * 5); //等待6秒
					break;
				}
				
				//防止死循环
				if(sc.getItemCount() * Const.NATIVE_TIMEOUT < totalTime) {
					TaskUtil.getInstance().getNativeTaskPool().createExecutorService();
					TaskUtil.getInstance().getFinishTaskPool().createExecutorService();
					Thread.sleep(1000 * 6); //等待6秒
					break;
				}
			}
			
			
			}
		} catch (Exception e) {	
			logger.error(ExceptionUtil.getExceptionMsg(e));			
		}
		}
    	
		
    }
}
